<script setup lang="ts">
import {add, del, getForm, getPage, update} from '@/api/namespace';
import {CrawlNamespaceForm, CrawlNamespacePageVO, CrawlNamespaceQuery} from '@/api/namespace/types';
import CrawlNamespaceSelector from "@/components/Crawl/CrawlNamespaceSelector.vue"
import CrawlTimePicker from "@/components/Crawl/CrawlTimePicker.vue"
import {ref} from "vue";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<CrawlNamespaceQuery>({
	pageNum: 1,
	pageSize: 10,
	nsCode: ""
});

const dataList = ref<CrawlNamespacePageVO[]>();

const dialog = reactive<DialogOption>({
	visible: false
});

const formData = reactive<CrawlNamespaceForm>({
	nsStatus: 1
});

const rules = reactive({
	nsName: [{required: true, message: '请输入名称', trigger: 'blur'}]
});

const nsSelector = ref()
const timePicker = ref()

/**
 * 查询
 */
function handleQuery() {
	loading.value = true;
	getPage(queryParams)
			.then(({data}) => {
				dataList.value = data.list;
				total.value = data.total;
			})
			.finally(() => {
				loading.value = false;
			});
}

/**
 * 重置查询
 */
function resetQuery() {
	queryFormRef.value.resetFields();
	queryParams.pageNum = 1;
	queryParams.nsCode = '';
	queryParams.createTimeStart = undefined
	queryParams.createTimeEnd = undefined
	nsSelector.value.reset();
	timePicker.value.reset();
	handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开表单弹窗
 *
 * @param dataId 数据ID
 */
function openDialog(dataId?: number) {
	dialog.visible = true;
	if (dataId) {
		dialog.title = '修改数据';
		getForm(dataId).then(({data}) => {
			Object.assign(formData, data);
		});
	} else {
		dialog.title = '新增数据';
	}
}

/**
 * 表单提交
 */
function handleSubmit() {
	loading.value = false;
	dataFormRef.value.validate((isValid: boolean) => {
		if (isValid) {
			const dataId = formData.id;
			if (dataId) {
				update(dataId, formData)
						.then(() => {
							ElMessage.success('修改成功');
							closeDialog();
							handleQuery();
						})
						.finally(() => (loading.value = false));
			} else {
				add(formData)
						.then(() => {
							ElMessage.success('新增成功');
							closeDialog();
							handleQuery();
						})
						.finally(() => (loading.value = false));
			}
		}
	});
}

/**
 * 关闭弹窗
 */
function closeDialog() {
	dialog.visible = false;
	resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
	dataFormRef.value.resetFields();
	dataFormRef.value.clearValidate();

	formData.id = undefined;
	formData.nsCode = undefined;
	formData.nsName = undefined;
	formData.nsStatus = 1;
}

/**
 * 删除
 */
function handleDelete(dataId?: number) {
	const dataIds = [dataId || ids.value].join(',');
	if (!dataIds) {
		ElMessage.warning('请勾选删除项');
		return;
	}

	ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		del(dataIds).then(() => {
			ElMessage.success('删除成功');
			resetQuery();
		});
	});
}

onMounted(() => {
	handleQuery();
});

function onSelectNsCode(nsCode: string) {
	queryParams.nsCode = nsCode;
}

function onSelectTimeRange(timeRange: [Date, Date]) {
	if (timeRange === null) {
		queryParams.createTimeStart = undefined;
		queryParams.createTimeEnd = undefined;
		return;
	}
	queryParams.createTimeStart = timeRange[0];
	queryParams.createTimeEnd = timeRange[1];
}

</script>

<template>
	<div class="app-container">
		<div class="search">
			<el-form ref="queryFormRef" :model="queryParams" :inline="true">
				<CrawlNamespaceSelector ref="nsSelector" @on-select="onSelectNsCode"/>
				<CrawlTimePicker ref="timePicker" @on-select="onSelectTimeRange"/>
				<el-form-item>
					<el-button type="primary" @click="handleQuery()">
						<i-ep-search/>
						搜索
					</el-button>
					<el-button @click="resetQuery()">
						<i-ep-refresh/>
						重置
					</el-button>
				</el-form-item>
			</el-form>
		</div>

		<el-card shadow="never">
			<template #header>
				<el-button type="success" @click="openDialog()"
				>
					<i-ep-plus/>
					新增
				</el-button
				>
				<el-button
						type="danger"
						:disabled="ids.length === 0"
						@click="handleDelete()"
				>
					<i-ep-delete/>
					删除
				</el-button
				>
			</template>
			<el-table
					highlight-current-row
					:data="dataList"
					v-loading="loading"
					@selection-change="handleSelectionChange"
					border
			>
				<el-table-column type="selection" width="55" align="center"/>
				<el-table-column label="空间名称" prop="nsName" width="200"/>
				<el-table-column label="空间编码" prop="nsCode" width="200"/>
				<el-table-column label="状态" align="center" width="100">
					<template #default="scope">
						<el-tag v-if="scope.row.nsStatus === 1" type="success">启用</el-tag>
						<el-tag v-else type="info">禁用</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="备注" prop="remark" align="center"/>
				<el-table-column label="创建时间" prop="createTime" width="200"/>
				<el-table-column fixed="right" label="操作" align="center" width="220">
					<template #default="scope">
						<el-button
								type="primary"
								link
								size="small"
								@click.stop="openDialog(scope.row.id)">
							<i-ep-edit/>
							编辑
						</el-button>
						<el-button
								type="primary"
								link
								size="small"
								@click.stop="handleDelete(scope.row.id)"
						>
							<i-ep-delete/>
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<pagination
					v-if="total > 0"
					v-model:total="total"
					v-model:page="queryParams.pageNum"
					v-model:limit="queryParams.pageSize"
					@pagination="handleQuery"
			/>
		</el-card>

		<el-dialog
				:title="dialog.title"
				v-model="dialog.visible"
				width="500px"
				@close="closeDialog"
		>
			<el-form
					ref="dataFormRef"
					:model="formData"
					:rules="rules"
					label-width="80px"
			>
				<el-form-item label="空间名称" prop="name">
					<el-input v-model="formData.nsName" placeholder="请输入名称"/>
				</el-form-item>
				<el-form-item label="空间编码" prop="code">
					<el-input :disabled=true v-model="formData.nsCode" placeholder="后端生成，无需输入"/>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-radio-group v-model="formData.nsStatus">
						<el-radio :label="1">正常</el-radio>
						<el-radio :label="0">停用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input
							v-model="formData.remark"
							type="textarea"
							placeholder="备注"
							:autosize="{ minRows: 2, maxRows: 4 }"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleSubmit">确 定</el-button>
					<el-button @click="closeDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
